<template>
  <div class="index">
    <div class="t_wind" v-if="isshowwind">
      <div
        style="width:100%;display:flex;justify-content:center;flex-direction: column;align-items: center;"
      >
        <div style="display:flex;justify-content: center;width:100%">
          <div
            style="background: #fff; border-radius:0.3rem; overflow: hidden;margin-top:1rem;width: 75%;height:60%"
          >
            <div style="width: 100%;">
              <img :src="selectObj.share_img ||'https://91haoka.cn/gth/static/img/kenan.jpg' " style="width: 100%; border-radius:0.3rem;height:5rem" />
            </div>
            <div class="flex" style="display:flex">
              <div style="width: 3.6rem; padding: 0.3rem;">
                <div style="font-size: 0.28rem;">{{selectObj.title}}</div>
                <div class="flexc" style="padding: 0.2rem 0;">
                  <div>
                    <img
                      :src="selectObj.logo"
                      style="width: 0.4rem; height: 0.4rem; border-radius: 0.2rem;"
                    />
                  </div>
                  <div
                    style="margin-left: 0.15rem; font-size: 0.24rem; color: rgb(64, 66, 71);"
                  >{{selectObj.shopname}}</div>
                </div>
                <div style="color: rgb(175, 179, 188); font-size: 0.2rem;">长按识别二维码进入下单链接</div>
              </div>
              <div style="width: 2rem; padding: 0.3rem 0;">
                <img
                  :src="img2"
                  style="width: 1.5rem; height: 1.5rem;margin-top:0.2rem;margin-left:0.2rem"
                />
              </div>
            </div>
          </div>
        </div>
        <div
          class="flex"
          style="display:flex;justify-content: space-between; margin-top: 0.6rem;width:75%"
        >
          <div
            style="width: 2.6rem; height: 0.8rem; font-size: 14px; background: #E4EDFF;  cursor: pointer; color: #005AFF; border-radius: 0.4rem;"
            class="flexcc"
            v-if="!weixin"
            @click="fenxianglogs()"
          >保存照片</div>
          <div
            style="width: 2.6rem; height: 0.8rem; font-size: 14px; background: #E4EDFF;  cursor: pointer; color: #005AFF; border-radius: 0.4rem;"
            class="flexcc"
            @click="fenxianglogs(2)"
            v-if="weixin"
          >保存照片</div>
          <div
            style="width: 2.6rem; height: 0.8rem; font-size: 14px; background:#005AFF; color: white; cursor: pointer; border-radius: 0.4rem;"
            class="flexcc"
            @click="fuzhi"
          >复制链接</div>
        </div>
      </div>
    </div>
    <!-- <van-nav-bar title="海报分享" left-arrow  @click-left="onClickLeft" /> -->
    <!-- <van-popup v-model="show" style="border-radius: 0.3rem;width:75%;">
    <div>
      <div style="background: #fff; border-radius:0.3rem; overflow: hidden;">
        <div><img :src="selectObj.share_img" style="width: 100%; border-radius:0.3rem;"></div>
        <div class="flex" style="display:flex">
          <div style="width: 3.6rem; padding: 0.3rem;">
            <div style="font-size: 0.28rem;">{{selectObj.title}}</div>
            <div class="flexc" style="padding: 0.2rem 0;">
              <div><img :src="selectObj.logo" style="width: 0.4rem; height: 0.4rem; border-radius: 0.2rem;"></div>
              <div style="margin-left: 0.15rem; font-size: 0.24rem; color: rgb(64, 66, 71);">{{selectObj.shopname}}</div>
            </div>
            <div style="color: rgb(175, 179, 188); font-size: 0.2rem;">长按识别二维码进入下单链接</div>
          </div>
          <div style="width: 2rem; padding: 0.3rem 0;"><img :src="img2" style="width: 1.5rem; height: 1.5rem;margin-top:0.2rem"></div>
        </div>
      </div>
      <div class="flex" style="justify-content: space-around; margin-top: 0.4rem;">
        <div style="width: 2rem; height: 0.8rem; font-size: 14px; background: rgb(64, 156, 255);  cursor: pointer; color: rgb(255, 255, 255); border-radius: 0.4rem;" class="flexcc" v-if="!weixin" @click="fenxianglogs()">保存照片</div>
        <div style="width: 2rem; height: 0.8rem; font-size: 14px; background: rgb(64, 156, 255);  cursor: pointer; color: rgb(255, 255, 255); border-radius: 0.4rem;" class="flexcc" @click="fenxianglogs(2)" v-if="weixin">保存照片</div>
        <div style="width: 2rem; height: 0.8rem; font-size: 14px; background: rgb(228, 237, 255); color: rgb(0, 90, 255); cursor: pointer; border-radius: 0.4rem;" class="flexcc" @click="fuzhi">复制链接</div>
      </div>
    </div>
    </van-popup>-->
    <van-popup v-model="fenxiangtulog2" style="width: 7.5rem; background: #fff !important;">
      <img :src="img3" style="width: 100%;" />
    </van-popup>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
import * as qiniu from "qiniu-js";

var h = document.documentElement.clientWidth / 7.5 + "px";
document.documentElement.style.fontSize = h;

export default {
  props: {
    // isshowwind: {
    //   type: Boolean,
    //   default: false
    // },
    selectObj: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  name: "query",
  data() {
    return {
      fenxiangtulog2: false,
      img3: "",
      img2: "",
      weixin: false,
      show: true,
      isshowwind: false
    };
  },
  created() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/micromessenger/i) == "micromessenger") {
      this.weixin = true;
    }
  },
  watch: {
    isshowwind: function(newValue, oldValue) {
      if (newValue) {
        document.title = "海报分享";
        console.log(this.selectObj.erweima);
        let url2 = this.selectObj.erweima;
        var d = document.createElement("div");
        d.setAttribute("id", "erweimadiv");
        document.body.appendChild(d);
        var qrcode = new QRCode(document.getElementById("erweimadiv"), {
          text: url2,
          width: 220,
          height: 220,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H
        });
        var canvas = document
          .getElementById("erweimadiv")
          .getElementsByTagName("canvas")[0];
        this.img2 = canvas.toDataURL("image/png");

        document.body.removeChild(d);
      }
    }
  },
  mounted() {
    //       document.title = "海报分享"
    // console.log('selectObj',this.selectObj)
    //       console.log(this.selectObj.erweima)
    //       let url2 = this.selectObj.erweima
    //       var d = document.createElement('div')
    //       d.setAttribute('id','erweimadiv')
    //       document.body.appendChild(d)
    //       var qrcode = new QRCode(document.getElementById('erweimadiv'), {
    //           text: url2,
    //           width: 220,
    //           height: 220,
    //           colorDark : "#000000",
    //           colorLight : "#ffffff",
    //           correctLevel : QRCode.CorrectLevel.H
    //       })
    //       var canvas = document.getElementById("erweimadiv").getElementsByTagName("canvas")[0];
    //       this.img2 = canvas.toDataURL("image/png");
    //       document.body.removeChild(d)
  },
  methods: {
    open: function() {
      this.isshowwind = true;
    },
    fuzhi: function() {
      this.copy(this.selectObj.erweima);
      this.isshowwind = false;
    },
    onClickLeft: function() {
      this.$router.back(-1);
    },
    fenxianglogs: function(item) {
      vant.Toast("进入后长按图片保存");
      setTimeout(() => {
        this.haibao(item);
      }, 1000);
      // this.xuanzhongde = item

      // this.isshowwind = false
    },
    haibao: function(weixin) {
      var that = this;
      var canvas = document.createElement("canvas");
      canvas.width = 750;
      canvas.height = 300;
      var ctx = canvas.getContext("2d");
      var canvas_h = 0;
      var img = new Image();
      let p = new Promise((res, rej) => {
        if (this.selectObj.share_img) {
          img.src = this.selectObj.share_img;
          img.setAttribute("crossOrigin", "Anonymous");
          img.onload = function() {
            let img_w = 750;
            let bili = 750 / img.width;
            let img_h = parseInt(img.height * bili);
            console.log(img_h);
            canvas_h = img_h;
            canvas.setAttribute("height", canvas_h + 260);
            ctx.drawImage(img, 0, 0, img_w, img_h); // 将图像绘制到Canvas上
            res("ok");
          };
          img.onerror = function(err) {
            // that.msg = JSON.stringify(err)
          };
        } else {
          vant.Toast("没有分享图不能分享");
          return;
          // res('ok')
        }
      });
      p.then(() => {
        var img2 = new Image();
        img2.src = this.img2;
        img2.setAttribute("crossOrigin", "Anonymous");
        img2.onload = function() {
          ctx.fillStyle = "#000";
          ctx.font = "bold 28px microsoft yahei";
          ctx.maxWidth = "400px";
          ctx.textBaseline = "top";

          let hang1 = that.selectObj.title.substring(0, 16) || "";
          let hang2 = that.selectObj.title.substring(16, 32) || "";
          ctx.fillText(hang1, 30, canvas_h + 35);
          ctx.fillText(hang2, 30, canvas_h + 70);

          // ctx.fillText(that.selectObj.title,30,canvas_h+30)

          ctx.drawImage(img2, 520, canvas_h + 30, 200, 200);

          ctx.fillStyle = "#000";
          ctx.font = "bold 24px microsoft yahei";
          ctx.lineHight = "40px";
          ctx.maxWidth = "300px";
          ctx.lineHeight = "40px";
          ctx.textBaseline = "top";
          ctx.fillText(that.selectObj.shopname, 85, canvas_h + 120);

          ctx.fillStyle = "rgb(175, 179, 188)";
          ctx.font = "20px microsoft yahei";
          ctx.textBaseline = "top";
          ctx.fillText("长按识别二维码 进入下单链接", 30, canvas_h + 190);

          var img22 = new Image();
          img22.src = that.selectObj.logo;
          img22.setAttribute("crossOrigin", "Anonymous");

          img22.onload = function() {
            ctx.drawImage(img22, 30, canvas_h + 110, 40, 40);
            var radius = 50;
            // 开始绘制圆角矩形路径
            ctx.beginPath();
            // 左上角
            ctx.arc(radius, radius, radius, Math.PI, Math.PI * 1.5);
            // 右上角
            ctx.arc(
              canvas.width - radius,
              radius,
              radius,
              Math.PI * 1.5,
              Math.PI * 2
            );
            // 右下角
            ctx.arc(
              canvas.width - radius,
              canvas.height - radius,
              radius,
              0,
              Math.PI * 0.5
            );
            // 左下角
            ctx.arc(
              radius,
              canvas.height - radius,
              radius,
              Math.PI * 0.5,
              Math.PI
            );
            // 结束绘制路径
            ctx.closePath();
            // 将路径限制到绘图区域内
            ctx.clip();
            ctx.drawImage(img22, 30, canvas_h + 110, 40, 40);

            var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            for (var i = 0; i < imageData.data.length; i += 4) {
              if (imageData.data[i + 3] == 0) {
                imageData.data[i] = 255;
                imageData.data[i + 1] = 255;
                imageData.data[i + 2] = 255;
                imageData.data[i + 3] = 255;
              }
            }
            ctx.putImageData(imageData, 0, 0);
            var url = canvas.toDataURL("image/png");

            //下载相关
            // var addElement = document.createElement('a')
            // addElement.href = url
            // addElement.download = "海报.png"
            // document.body.appendChild(addElement)
            // addElement.click();
            // document.body.removeChild(addElement);

            const blob = that.base64ImgtoFile(url);

            that.uploadok(blob, weixin);
          };
        };
      });
    },
    base64ImgtoFile(dataurl, filename = "file") {
      //将base64格式分割：['data:image/png;base64','XXXX']
      const arr = dataurl.split(",");
      // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
      // image/png
      const mime = arr[0].match(/:(.*?);/)[1]; //image/png
      //[image,png] 获取图片类型后缀
      const suffix = mime.split("/")[1]; //png
      const bstr = atob(arr[1]); //atob() 方法用于解码使用 base-64 编码的字符串
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      });
    },
    getRandomChar: function(len = 11) {
      var x = "0123456789qwertyuioplkjhgfdsazxcvbnm"; // 需要什么字符这里添加
      var tmp = "";
      var timestamp = new Date().getTime();
      for (var i = 0; i < len; i++) {
        tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
      }
      return timestamp + tmp;
    },
    uploadok: function(file, weixin) {
      let name = this.getRandomChar() + "." + file.name.split(".")[1];
      var that = this;
      axios.post(`/api/qiniu/uploadtoken`, { name: name }).then(response => {
        if (response.data.msg.code == 0) {
          const observer = {
            next(res) {
              console.log(res);
            },
            error(err) {
              console.log(err);
            },
            complete(res) {
              if (weixin == 2) {
                location.href = "https://gperson.gantanhaokeji.top/" + res.key;
              } else {
                var addElement = document.createElement("a");
                addElement.href =
                  "https://gperson.gantanhaokeji.top/" + res.key + "?attname=";
                addElement.download = "海报.png";
                document.body.appendChild(addElement);
                addElement.click();
                document.body.removeChild(addElement);
              }
            }
          };
          const observable = qiniu.upload(
            file,
            name,
            response.data.data.token,
            {},
            {}
          );
          const subscription = observable.subscribe(observer); // 上传开始
        } else {
          this.$message.error(response.data.msg.info);
        }
      });
    }
  }
};
</script>
<style scoped lang="less">
.t_wind {
  width: 100vw;
  height: 100vh;
  position: fixed;
  display: flex;
  align-items: center;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 99;
}
</style>

<style scoped lang="less">
</style>
